<template>
  <div>
    <div v-show="showL">
      <el-row :gutter="20">
        <el-col :span="12" :offset="6" class="trans">
          <h1>登录</h1>
          <!--        <div>{{test}}</div>-->
          <el-form class="trans" :rules="rules" :model="form" ref="LRef">
            <p></p>
            <el-form-item label="邮箱" prop="id">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input v-model="form.password" type="password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="Login">登录</el-button>
<!--              <el-button type="primary" round @click="CLogin">cookie登录</el-button>-->
              <el-button type="success" round @click="toRegist">去注册</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div v-show="showR">
      <el-row :gutter="20">
        <el-col :span="12" :offset="6" class="trans">
          <h1>注册</h1>
          <el-form class="trans" ref="RRef" :model="form" :rules="rules">
            <el-form-item label="邮箱" prop="id">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
            <el-form-item label="昵称" prop="id">
              <el-input v-model="form.nickname"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="id">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input v-model="form.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="再次输入密码" prop="pass">
              <el-input v-model="form.repassword" type="password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" round @click="toLogin">去登录</el-button>
              <el-button type="success" round @click="Regist">注册</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import '../assets/css/global.css'
import {Base64} from 'js-base64';
import qs from 'qs'
import axios from "axios";

export default {
  data() {
    return {
      showL: true,
      showR: false,
      form: {
        email: "",
        password: "",
        repassword: "",
        nickname: "",
        phone: ""
      },
      //表单的验证规则对象
      rules: {
        email: [
          {required: true, message: '请输入用户账户（邮箱）', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 6, message: '长度在3到6个字符之间', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    //登录
    async Login() {
      //表单预校验
      this.$refs.LRef.validate(async valid => {
        //通过预验证则valid=true
        if (!valid) {
          this.$message.error("账号或密码格式错误");
          return;
        }
        // const {data:res} = await axios.get(axios.defaults.baseURL+'login',this.form);
        axios({
          methods: 'get',
          url: axios.defaults.baseURL + 'login',
          params: this.form
        }).then((res) => {
          // this.$message.success("接收到了信息")
          console.log(res)
              if (res.data.code === '000000') {
                this.$message.success("登陆成功")
                this.$router.push('/index');
                this.$cookies.set("uid", res.data.content.uid, 36000);
                this.$cookies.set("password", this.form.password, 36000);
                this.$cookies.set("token", res.data.content.token, 36000);
                this.$cookies.set("nickname", res.data.content.nickname, 36000);
                // axios.defaults.headers.common['Authorization'] = "Bearer " + sessionStorage.getItem('token');;
                sessionStorage.setItem("uid", res.data.content.uid);
                sessionStorage.setItem("token", res.data.content.token);
                sessionStorage.setItem("nickname", res.data.content.nickname);
              }else{
                this.$message.error(res.data.desc)
              }
            })
            // .catch((error) => {
            //   console.log(error);
            // });
        // if(res.code==="000000"){
        //   this.$message.success("登陆成功");
        //   //设置cookie，时间为1hour
        //   this.$cookies.set("uid",res.content.uid,3600);
        //   this.$cookies.set("password",this.form.password,3600);
        //   this.$cookies.set("Token",res.content.Token,3600);
        //   sessionStorage.setItem("uid",res.content.uid);
        //   sessionStorage.setItem("token",res.content.Token);
        //   await this.$router.push('/index');
        // }else{
        //   this.$message.error(res.desc);
        // }
      })
    },
    //cookie登录
    async CLogin() {
      if (this.$cookies.get("uid") != null && this.$cookies.get("password") != null) {
        // this.form.pass=Base64.decode(this.$cookies.get("pass"));
        this.form.password = this.$cookies.get("password");
        this.form.email = this.$cookies.get("email");
        let {data: res} = await this.$http.post(axios.defaults.baseURL + 'login', this.form);
        if (res.code === "000000") {
          this.$message.success("cookie登陆成功");
          sessionStorage.setItem("uid", res.content.userId);
          sessionStorage.setItem("token", res.content.token);
          await this.$router.push('/index');
        } else {
          this.$message.error(res.desc);
        }
      } else {
        this.$message.error("未找到cookie");
      }
    },
    //注册
    async Regist() {
      if (this.form.email.length === 0) {
        this.$message.error("邮箱不得为空")
        return;
      }
      this.$refs.RRef.validate(async valid => {
        if (!valid) {
          this.$message.error("输入格式错误")
          return;
        }
        if (this.form.password !== this.form.repassword) {
          this.$message.error("两次输入密码不一致")
          return;
        }

        const {data: res} = await this.$http.post(axios.defaults.baseURL + 'auth/register', this.form)
        if (res.code === "000000") {
          this.$message.success("注册成功");
          this.toLogin();
        } else {
          this.$message.error(res.desc);
        }
        // await this.$http.post(
        //     'http://localhost:8081/auth/register',
        //     JSON.stringify(this.form),
        //     {
        //       headers: {
        //         'Content-Type': 'application/json',
        //         'Authorization': 'Bearer '
        //       }
        //     }
        // )

      })
    },

    toRegist() {
      this.showL = false;
      this.showR = true;
      this.form.passAgain = "";
      this.form.pass = "";
      this.form.id = "";
    },
    toLogin() {
      this.showL = true;
      this.showR = false;
      this.form.passAgain = "";
      this.form.pass = "";
      this.form.id = "";
    }
  }
}
</script>

<style scoped>
.trans {
  border-radius: 40px;
  /*margin:200px 200px;*/
  background-color: #ffffff;
  /* border:1px solid black; */
  opacity: 0.8;
}
</style>
